package van.planifolia.interceptor;

import com.alibaba.fastjson.JSON;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import van.planifolia.result.ComResult;
import van.planifolia.util.JWTTool;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Intellij IDEA<br>
 *
 * @author Planifolia.Van
 * @version 1.0
 * @date 2022/11/23 18:23
 */
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 拿到用户携带的token信息
        String token = request.getHeader("token");
        // 校验tk信息,tk不为空并且tk通过校验则允许继续访问
        if (!StringUtils.isEmpty(token)) {
            if (JWTTool.verifyToken(token)) {
                return true;
            }
        }
        // 修改编码格式
        response.setContentType("application/json;charset=utf-8");
        // 否则我们使用PrintWriter对象向前端输出一个错误json，并且拒绝继续访问
        String json = JSON.toJSONString(new ComResult(5001, "用户未登录"));
        response.getWriter().print(json);
        response.getWriter().flush();
        response.getWriter().close();
        return false;
    }
}
